package com.zy.模式匹配.模式匹配类型

object Test {

  def main(args: Array[String]): Unit = {

    // 匹配常量 匹配不同的数据类型的各种数据
    def describedConst(x: Any): String = x match {
      case 1 => "Num one"
      case "hello" => "hi"
      case true => "is true"
      case _ => "nothing"
    }

    println(describedConst("hello"))
    println(describedConst(true))
    println(describedConst(0.3))

    println("=======================")

    // 匹配类型 根据数据类型进行匹配
    def describedType(x: Any): String = x match {
      case i: Int => "Int"
      case s: String => "String"
      // 无法判断泛型
      case list: List[Int] => "List"
      // Array的泛型可以生效
      case arr: Array[String] => "Array"
      case _ => "N/A"
    }

    println(describedType(1))
    println(describedType(List(1, 2, 3)))
    println(describedType(List("1", "2")))
    println(describedType(Array("1", "2")))
    println(describedType(Array(1, 2)))
    println(describedType(0.2))

    println("=======================")

    // 匹配数组 匹配数组数据的各种情况
    def describedArray(array: Array[Any]): String = array match {
      case Array(0) => "只存在一个0的数组"
      case Array(x, y) => "存在两个元素的数组"
      case Array(0, _*) => "以0开头的数组"
      case Array(x, 1, y) => "中间为1的三元素数组"
      case _ => "其他情况"
    }

    println(describedArray(Array[Any](0)))
    println(describedArray(Array[Any](0, 2)))
    println(describedArray(Array[Any](3, 1, "123")))

    println("=======================")

    // 匹配列表 匹配模式与数组相似
    def describedList(list: List[Any]): String = list match {
      case List(0) => "只存在一个0的列表"
      case List(x, y) => "存在两个元素的列表"
      case List(0, _*) => "以0开头的列表"
      case List(x, 1, y) => "中间为1的三元素列表"
      case first :: second :: reset => "表示至少存在三个元素(可以拼接)"
      case _ => "其他情况"
    }

    println(describedList(List[Any](0)))
    println(describedList(List[Any](0, 2)))
    println(describedList(List[Any](3, 1, "123")))


    println("=======================")

    // 元祖匹配
    def describedTuple(tuple: Any): String = tuple match {
      case (0, _) => "以0开头的元祖"
      case (a, b) => "两个元素的双元素元祖"
      case (a: Int, b: Int, c: String) => "前两个Int，第三个是String"
      case _ => "其他情况"
    }

    println(describedTuple((1, 2)))
    println(describedTuple((0, 1)))
    println(describedTuple((1, 2, "3")))

  }

}
